package org.wdl.hotelAppTest.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {

	//添加cookie
	public static void addCookie(String loginname, String password, int age, String cookieName, HttpServletResponse response, HttpServletRequest request) {
		Cookie  cookie = getCookieByName(cookieName, request);
		if(cookie != null) {
			cookie.setValue(loginname+"#"+password);
		}else {
			//登录名和密码通过#进行连接
			cookie = new Cookie(cookieName, loginname+"#"+password);
		}
		
		//设置cookie的有效时间
		cookie.setMaxAge(age);
		System.out.println("request.getContextPath():"+request.getContextPath());
		//设置cookie的作用域
		cookie.setPath(request.getContextPath());
		
		//把Cookie添加到响应对象中
		response.addCookie(cookie);
	}
	
	//通过cookie名获取cookie
	public static Cookie getCookieByName(String cookieName,HttpServletRequest request) {
			Cookie[]  cookies = request.getCookies();
				
			if(cookies != null) {
				for (Cookie cookie2 : cookies) {
					if(cookie2.getName().equals(cookieName)) {
						//类似于第二三次保存该项目的用户名和密码到cookie中，没必要new cookie，可直接改值
						return  cookie2;
					}
				}
			}
			return null;
	}

	public static void removeCookie(String cookieName, HttpServletRequest request, HttpServletResponse response) {
		Cookie  cookie = getCookieByName(cookieName, request);
		
		if(cookie != null) {
			//设置cookie的有效时间
			cookie.setMaxAge(0);
			//设置cookie的作用域
			cookie.setPath(request.getContextPath());
			
			//把Cookie添加到响应对象中
			response.addCookie(cookie);
			
		}
	}

}
